package inits

import (
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"good-server/basic/config"
	"good-server/basic/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func init() {
	config.Init()
	InitNacos()
	InitMysql()
	InitElas()
}

func InitElas() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://14.103.235.214:9200",
		},
	}
	global.Es, _ = elasticsearch.NewClient(cfg)
}

func InitNacos() {

	appends := config.AppConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         appends.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}

	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      appends.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(appends.Port),
			Scheme:      "http",
		},
	}

	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: appends.DataId,
		Group:  appends.Group,
	})

	var good config.Config
	json.Unmarshal([]byte(content), &good)

	global.GoodNacos = good

}

func InitMysql() {
	var err error
	appends := global.GoodNacos
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", appends.Mysql.User, appends.Mysql.Password, appends.Mysql.Host, appends.Mysql.Port, appends.Mysql.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		panic("mysql连接失败")
	}
	fmt.Println("mysql连接成功")
}
